package chapter02

import scala.collection.mutable

object Test33_SeriorFunction {
  def main(args: Array[String]): Unit = {
    val list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)
    val nestedList: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6), List(7, 8, 9))
    val wordList: List[String] = List("hello world", "hello atguigu", "hello scala")
    //过滤 filter
    //过滤出符合条件的元素
    println(list.filter(e=>{e%2==0}))
    //映射 map操作
    println(list.map(e=>{e+1}))
    val list1 = list.map(e => {
      (e, 1)
    })
    println(list1)
    //使用map实现filter
    val list2 = list.map(e => {
      if (e % 2 == 0) e
    })
    println(list2)
    //扁平化
    println(nestedList.flatten)
    //先映射 后扁平化
    println(wordList.map(e=>e.split(" ").toList).flatten)
    println(wordList.flatMap(e => e.split(" ").toList))
    //分组
    println(list.groupBy(e=>e%3))
    val list3 = {
      List(List("张三", "男"), List("李四", "女"), List("王五", "女"), List("田七", "女"))
    }
    println(list3.groupBy(_(1)))
    //Reduce简化（归约） ：通过指定的逻辑将集合中的数据进行聚合，从而减少数据，最终获取结果。
    val list4 = List(1,2,3,4)
    println(list4.reduce((x,y)=>x+y))
    println(list4.reduce((x,y)=>x-y))
    println(wordList.reduce((x,y)=>x+" "+y))
    //从右向左
    println(list4.reduceRight(_-_))
    //Fold折叠：化简的一种特殊情况。 第一个值为初始值 第二个为运算规则
    println(list4.fold(10)((x,y)=>x+y))
    //1-(2-(3-(4-10))) = 1-(2-(3+6)) = 1-(2-9)=1+7=8
    println(list4.foldRight(10)((x,y)=>x-y))
    //两个map合并成一个map
    val map1 = mutable.Map("a"->1, "b"->2, "c"->3)
    val map2 = mutable.Map("a"->4, "b"->5, "d"->6)
    val map3 = map1.foldLeft(map2)((map, kv) => {
      val k = kv._1
      val v = kv._2
      map(k) = map.getOrElse(k, 0) + v
      map
    })
    println(map3)
    val m = List(Map("姓名"->"张三","语文"->87,"数学"->88,"英语"->78),
      Map("姓名"->"李四","语文"->82,"数学"->81,"英语"->90),
      Map("姓名"->"王五","语文"->80,"数学"->74,"英语"->79))
    //平均分数
    val b = m.map(e=>e.getOrElse("数学",-100).toString.toInt)
    println(b.sum/b.length)
    //每个人的平均分
    val list5 = m.map(e => {
      e.values.drop(1).map(k=>{k.toString.toInt}).sum/3
    })
    println(list5)
    val stringList = {
      List("Hello Scala Hbase kafka", "Hello Scala Hbase", "Hello Scala", "Hello")
    }
    //
    val functionToMap = stringList.flatMap(e => e.split(" ")).groupBy(e=>e)
    println(functionToMap.map(kv=>{kv._1->kv._2.size}))
    val tupleList =
      List(("Hello Scala Spark World ", 4), ("Hello Scala Spark", 3), ("Hello Scala", 2), ("Hello", 1))

    val tuples = tupleList.flatMap(e => {
      (e._1.split(" ").toList.map(f => {
        (f, e._2)
      }))
    }).groupBy(e=>{e._1}).mapValues(e=>{e.map(f=>{f._2}).sum})
    println(tuples)
  }
}
